package com.smalltao.core.utils;

import com.baomidou.mybatisplus.core.toolkit.ClassUtils;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.cglib.beans.BeanMap;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author smallTao.liu
 * @version V1.0
 * @description Bean工具类
 * @date 2018/11/23 12:52
 */
public class BeanUtils {

    private BeanUtils() {
    }

    public static Map<String, Object> beanToMap(Object bean) {
        return null == bean ? null : BeanMap.create(bean);
    }

    public static <T> T mapToBean(Map<String, Object> map, Class<T> clazz) {
        T bean = ClassUtils.newInstance(clazz);
        BeanMap.create(bean).putAll(map);
        return bean;
    }

    public static <T> List<Map<String, Object>> beansToMaps(List<T> beans) {
        return CollectionUtils.isEmpty(beans) ? Collections.emptyList() : beans.stream().map(com.baomidou.mybatisplus.core.toolkit.BeanUtils::beanToMap).collect(Collectors.toList());
    }

    public static <T> List<T> mapsToBeans(List<Map<String, Object>> maps, Class<T> clazz) {
        return CollectionUtils.isEmpty(maps) ? Collections.emptyList() : maps.stream().map((e) -> mapToBean(e, clazz)).collect(Collectors.toList());
    }
}
